package com.example.api.websocket.component;

import com.example.api.websocket.utils.WebSocketUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * @name: OneWebSocket
 * @description:
 * @author: xw.s
 * @date: 2021/6/10-10:36
 */
@Component
@ServerEndpoint(value = "/websocket/{username}")
@Slf4j
public class WebSocketComponent {

    /**
     * 建立连接
     * @param username
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam("username") String username, Session session){
        WebSocketUtils.living_session_cache.put(username, session);
        String message = "欢迎" + username + "进入聊天室，当前在线人数" + WebSocketUtils.living_session_cache.size();
        log.info(message);
        WebSocketUtils.sendMessageAll(message);
    }

    /**
     * 有人发言
     * @return
     */
    @OnMessage
    public void onMessage(@PathParam("username") String username, String message) {
        log.info(username + "发言：" + message);
        WebSocketUtils.sendMessageAll(message);
    }

    /**
     * 关闭session
     * @return
     */
    @OnClose
    public void onClose(@PathParam("username") String username, Session session){
        log.info(username + "断开连接");
        WebSocketUtils.living_session_cache.remove(username);
        WebSocketUtils.sendMessageAll(username + "离开了聊天室");
        try {
            session.close();
        } catch (IOException e) {
            log.error(username + "关闭session出现异常：" + e);
        }
    }

    /**
     * 出现错误
     * @return
     */
    @OnError
    public void onError(Session session, Throwable throwable){
        log.info(session + "发生ERROR");
        try {
            session.close();
        } catch (IOException e) {
            log.error(session + "发生ERROR后" + "，关闭session出现异常：" + e);
        }
    }

    @GetMapping("/chat/{sender}/to/{receive}")
    public void onMessage(@PathVariable("sender") String sender, @PathVariable("receive") String receive, String message) {
        WebSocketUtils.sendMessage(WebSocketUtils.living_session_cache.get(receive), "[" + sender + "]" + "-> [" + receive + "] : " + message);
    }
}





























